<?php
namespace app\home\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
require_once (APP_PATH . 'api/RewardApi.php');
require_once (APP_PATH . 'api/FinanceApi.php');
class Pay extends Base {
	
    //空操作
    public function _initialize(){
        parent::_initialize();
        //钱包配置
    }

    public function _empty(){
        header("HTTP/1.0 404 Not Found");
        $this->display('Public:404');
    }
   
    /*
     * $year 年份
     * $month 月份
     * $week  
     */    
    public function aaaa(){
    	$aa = rand(000000, 999999);
	 	$num = date('Y').date('m').date('d').$aa;
	 	
    }
   	
    public function transfer(){
    	$map['transfer'] = 1;
    	$list = Db::name('App_account_type')->where($map)->select();
    	foreach($list as $k=>$v){
    		$jifen = Db::name('App_member_account')->field('account_type_'.$list[$k]['id'])->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    		$bb['name'] = $list[$k]['name'];
    		$bb['id'] = $list[$k]['id'];
    		$bb['num'] = $jifen['account_type_'.$list[$k]['id']];
    		$aa[] = $bb;
    	}
    	//转张记录
    	$where['member_id'] =$_SESSION['think']['USER_KEY_ID'];
    	$where['finance_type'] = 3;
    	$count =db('App_finance')->where($where)->count();
    	$finance = db('App_finance')->where($where)->paginate(10);//获取当前登录的用户的转账记录(带分页)
    	$page = $finance->render();
    	$finance = $finance->all();
    	foreach($finance as $m=>$n){
    		$account_type =db('App_account_type')->where(array('id'=>$finance[$k]['account_type']))->find();
    		$finance[$k]['jifen'] = $account_type['name'];
    	}
    	
    	$this->assign('finance',$finance);
    	$this->assign('aa',$aa);
    	$this->assign('page', $page);
    	return $this->fetch();
    }
    /**
     * 转账方法
     */
    public function transfer_add(){
    	$account=input('account',"");//获取转账的用户
    	$pwd=input("pwd","");//获取二级密码
    	$money=input("money",0);//获取转的金额 默认是0
    	$type = input('type');//获取转账的币种
    	
    	$session = session::get();
    	$where['userId'] = $session['USER_KEY_ID'];
    	$user = Db::name('Users')->where($where)->find();
    	
    	if(empty($account)){
    		$msg['status']=-1;
    		$msg['info']="请填写用户名";
    		return json($msg);exit();
    	}
    	if(empty($pwd)){
    		$msg['status']=-2;
    		$msg['info']="请填写密码";
    		return json($msg);exit;
    	}
    	if($user['payPwd']!=md5($pwd)){
    		$msg['status']=-3;
    		$msg['info']="交易密码错误";
    		return json($msg);exit;
    	}
    	if(empty($money)){
    		$msg['status']=-5;
    		$msg['info']="请输入转账金额";
    		return json($msg);exit;
    	}
    	//账户信息
    	//获取要转账的币种的余额
    	//获取所有的币种余额
    	
    	$one = db('App_member_account')->field('account_type_'.$type)->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    	$account_type_one = M('App_account_type')->where(array('id'=>$type))->find();//获取币种的信息
    	if($one['account_type_'.$type]<$money){
    		$msg['status']=-6;
    		$msg['info']= $account_type_one['name']."不足";
    		return json($msg);exit;
    	}
    	$member=db("Users")->where(['loginName'=>$account])->find();
    	if($member['userId'] == $_SESSION['think']['USER_KEY_ID']){
    		$msg['status']=-4;
    		$msg['info']="不能给自己转账!";
    		return json($msg);exit;
    	}
    	
    	if(empty($member)){
    		$msg['status']=-4;
    		$msg['info']="无效用户";
    		return json($msg);exit;
    	}
    
    	// 		$transfer_bili=!empty($this->config['transfer_bili'])?$this->config['transfer_bili']:10;//手续费
    	// 		$t_bili=(100-$transfer_bili)/100;
    	// 		$t_bili=1;
    	Db::startTrans();
    	//添加记录
    	$re[]=db("App_member_account")->where(['member_id'=>$_SESSION['think']['USER_KEY_ID']])->setDec('account_type_'.$type,$money);
    	$re[]=db("App_member_account")->where(['member_id'=>$member['userId']])->setInc('account_type_'.$type,$money);
  	
    	$re[]=$this->addTransfer($_SESSION['think']['USER_KEY_ID'], $member['userId'], 1, "转账给".$member['loginName'],$money);
    	$re[]=$this->addTransfer($member['userId'], $_SESSION['think']['USER_KEY_ID'], 2, "收到转账".$this->member['loginName'],$money);
    	$Finance = new \FinanceApi();
    	$re[]=$Finance->addFinance($_SESSION['think']['USER_KEY_ID'], 3, "转账给".$member['loginName'].$account_type_one['name']. $money,'2',$money,$type);
    	$re[]=$Finance->addFinance($member['userId'], 3, "收到转账".$this->member['loginName'].$account_type_one['name']. $money, '1',$money,$type);
    
    	if(in_array("false",$re)){
    		Db::commit();
    		$msg['status']=1;
    		$msg['info']="转账成功";
    		return json($msg);exit;
    	}else{
    		Db::rollback();
    		$msg['status']=-7;
    		$msg['info']="转账失败";
    		return json($msg);exit;
    	}    
    }
    /**
     *
     * 添加转账记录
     * @param int $member_id  用户id
     * @param int $receive_id  发送或者接受的id(也是用户的)
     * @param int $type   1为发送，2为接受
     * @param String $content 本次描述
     * @param int $money 本次转账金额
     * @return 成功返回true；失败返回false
     */
    private function addTransfer($member_id,$receive_id,$type,$content,$money){
    	$data['member_id']=$member_id;
    	$data['receive_id']=$receive_id;
    	$data['type']=$type;
    	$data['content']=$content;
    	$data['add_time']=time();
    	$data['status']=1;
    	$data['money']=$money;
    	$re=db("App_transfer")->insert($data);
    	if($re){
    		return true;
    	}else{
    		return false;
    	}
    
    }

    /**
     * 验证用户纯不纯在
     */
    public function checkout_user(){
    	$account = input('account');
    	$member = db('Users')->where(array('loginName'=>$account))->find();
    	if($member){
    		if($member['userId'] == $_SESSION['think']['USER_KEY_ID']){
    			$data['info'] = '不能给自己转账!';
    			$data['status'] = -1;
    			return json($data);
    		}else{
    			$data['info'] = '存在';
    			$data['status'] = 1;
    			return json($data);
    		}
    		
    	}else{
    		$data['info'] = '不存在';
    		$data['status'] = -1;
    		return json($data);
    	}
    }
    /**
     * 积分之间相互转换
     */
    public function currency_conversion(){
    	$list = db('App_account_type')->select();
    	foreach($list as $k=>$v){
    		if(!empty($list[$k]['conversion'])){
    			$conversion = explode(',', $list[$k]['conversion']);
    			$where1['id'] = array('in',$conversion);
    			$arr = db('App_account_type')->field('name,id')->where($where1)->select();
    			foreach($arr as $m=>$n){
    				$bb['name'] =$list[$k]['name'].'转换'.$arr[$m]['name'];
    				$bb['id'] =$list[$k]['id'].'_'.$arr[$m]['id'];
    				$jifen = db('App_member_account')->field('account_type_'.$list[$k]['id'])->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    				$bb['first_jifen_name'] = $list[$k]['name'];
    				$bb['first_jifen_id'] = $list[$k]['id'];
    				$bb['first_jifen'] = $jifen['account_type_'.$list[$k]['id']];
    				$aa[] = $bb;
    			}
    		}
    	}
    	//转换记录
    	$where['member_id'] =$_SESSION['think']['USER_KEY_ID'];
    	$where['finance_type'] = 2;
    	$finance = Db::name('App_finance')->where($where)->order('add_time desc')->paginate(10);
//     	dump($finance);
    	$page = $finance->render();
    	// 		dump($finance);die();
    	$this->assign('finance',$finance);
    	$this->assign('page', $page);
    	$this->assign('aa',$aa);
    	return $this->fetch();
    }
    /**
     * 会员转换积分方法实现
     */
    public function transformation_ok(){
    	$type=input('type');
    	$num=input("money");
   		$password=input("password");
   		$session = session::get();
   		$user = Db::name('Users')->where(array('userId'=>$session['USER_KEY_ID']))->find();
    	if(empty($num)){
    		$msg['status']=-1;
    		$msg['info']="请填写转换金额";
    		return json($msg);exit();
    	}
    	
    	if($num<0){
    		$msg['status']=-2;
    		$msg['info']="请输入正数";
    		return json($msg);exit;
    	}
    	//截取类型
    	$arr = explode('_',$type);
    	$one = Db::name('App_member_account')->field('account_type_'.$arr[0])->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    	$two = Db::name('App_member_account')->field('account_type_'.$arr[1])->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    	$account_type_one = Db::name('App_account_type')->where(array('id'=>$arr[0]))->find();
    	$account_type_two = Db::name('App_account_type')->where(array('id'=>$arr[1]))->find();
    	if($num>$one['account_type_'.$arr[0]]){
    		$msg['status']=-3;
    		$msg['info']='您的'.$account_type_one['name'].'不足';
    		return json($msg);exit;
    	}
	   	if(empty($password)){
	   		$msg['status']=-4;
	   		$msg['info']="请输入交易密码";
	   		return json($msg);exit;
	   	}
	   	if(empty($user['payPwd'])){
	   		$msg['status'] = -7;
	   		$msg['info'] = "请先设置二级密码";
	   		return json($msg);exit;
	   	}
	   	if($user['payPwd'] != md5($password)){
	   		$msg['status']=-5;
	   		$msg['info']="交易密码错误，请重新输入";
	   		return json($msg);exit;
	   	}
    	$data['member_id']=$_SESSION['think']['USER_KEY_ID'];
    	$data['num']=$num*(1);
    	$data['fee']=0.00;
    	$data['all_num']=$num;
    	$data['add_time']=time();
    	$data['type']=$type;
    	$data['status']=1;
    	Db::startTrans();
    	$re[] = Db::name("App_zhuanhuan")->add($data);//添加转账记录
    	//减钱加钱
        $finance = new \FinanceApi();
    	$whereuser['member_id']=$_SESSION['think']['USER_KEY_ID'];
    	$re[] = Db::name('App_member_account')->where($whereuser)->setDec('account_type_'.$account_type_one['id'],$num);
    	$re[] = Db::name('App_member_account')->where($whereuser)->setInc('account_type_'.$account_type_two['id'],$num);
    	$re[] = $finance->addFinance($_SESSION['think']['USER_KEY_ID'],2,$account_type_one['name']."转换".$account_type_two['name'],2,$num,$account_type_one['id']);
    	$re[] = $finance->addFinance($_SESSION['think']['USER_KEY_ID'],2,$account_type_one['name']."转换".$account_type_two['name'],1,$num,$account_type_two['id']);
    	if(in_array("false", $re)){
    		Db::rollback();
    		$msg['status']=-6;
    		$msg['info']="转换失败";
    		return json($msg);exit();
    	}else{
    		Db::commit();
    		$msg['status']=1;
    		$msg['info']="转化成功";
    		return json($msg);exit();
    	}
    }
    /**
     * 激活页面
     */
    public function activation(){
    	
    	if($_POST){
    		$map['account'] = input('account');
    	}
    	$session = session::get();
    	$map['status']=0;
    	$map['baodan'] = $session['USER_KEY_ID'];
    	$list = Db::table('wst_app_member_relation')
								    	->alias('a')
								    	->join('users w','a.member_id = w.userId')
								    	->order('member_id desc')
								    	->where($map)
								    	->select();
    	foreach($list as $k=>$v){
    		$zhuce = Db::name('Users')->where(array('userId'=>$list[$k]['zhuceid']))->find();
    		$list[$k]['zhuce_name'] = $zhuce['loginName'];
    		$jiedian = Db::name('Users')->where(array('userId'=>$list[$k]['jiedianid']))->find();
    		$list[$k]['jiedian_name'] = $jiedian['loginName'];
    	}
    	//查看后台会员级别
    	$level = Db::name('App_level')->where(array('status'=>1))->select();
    	$where['jihuo'] = 1;
    	$account = db('App_account_type')->where($where)->find();
    	$member_account = M('app_member_account')->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->find();
    	$bb['money'] = $member_account['account_type_'.$account['id']];
    	$bb['name'] = $account['name'];
    	//查看自己历史激活人
    	$where_old['status'] = 1;
    	$where_old['baodan'] = $session['USER_KEY_ID'];
    	$list_old = Db::table('wst_app_member_relation')
								    	->alias('a')
								    	->join('users w','a.member_id = w.userId')
								    	->order('member_id desc')
								    	->where($where_old)
								    	->select();
    	foreach($list_old as $m=>$n){
    		$zhuce = Db::name('Users')->where(array('userId'=>$list_old[$m]['zhuceid']))->find();
    		$list_old[$m]['zhuce_name'] = $zhuce['loginName'];
    		$jiedian = Db::name('Users')->where(array('userId'=>$list_old[$m]['jiedianid']))->find();
    		$list_old[$m]['jiedian_name'] = $jiedian['loginName'];
    	}
    	$this->assign('list_old',$list_old);
    	
    	//个人信息
    	$member = Db::name('App_member_relation')->where(array('member_id'=>$session['USER_KEY_ID']))->find();
    	$my_jiedian = Db::name('Users')->where(array('userId'=>$member['jiedianid']))->find();
    	$my_tuijian = Db::name('Users')->where(array('userId'=>$member['zhuceid']))->find();
    	$member['jiedian_name'] = $my_jiedian['loginName'];
    	$member['zhuce_name'] = $my_tuijian['loginName'];
    	$this->assign('member',$member);
    	$this->assign('bb',$bb);
    	$this->assign('level',$level);
    	$this->assign('list',$list);
    	return $this->fetch();	
    }
    /**
     * 详情页(激活)
     */

    public function detial(){
    	$session = session::get();
    	$id = input('member_id');
    	//$level = I('level');
    	$member = Db::name('App_member_relation')->where(array('member_id'=>$id))->find();
    	$zhuce = Db::name('Users')->where(array('userId'=>$member['zhuceid']))->find();
    	$member['zhuce_name'] = $zhuce['loginName'];
    	//$level = Db::name('App_level')->where(array('id'=>input('level')))->find();
//     		if(!empty($level['goods_id'])){
//     			$arr_gid = explode(',', $level['goods_id']);//获取该等级的商品
//     		}
//     		if(!empty($level['goodsnum'])){
//     			$arr_gnum = explode(',', $level['goodsnum']);//获取该等级的商品的数量
//     		}
//     		for($i=0;$i<count($arr_gid);$i++){//遍历出对应的币种 和开通后获得的奖励
//     			$arr[$arr_gid[$i]]['id'] = $arr_gid[$i];
//     			$arr[$arr_gid[$i]]['gnum'] =$arr_gnum[$i];
//     		}
//     		$goods = Db::name('Goods')->select();//获取所有的商品
//     		foreach($goods as $k=>$v){
//     			if(in_array($goods[$k]['id'],$arr_gid)){
//     				$goods[$k]['status'] = 1;//让当前拥有的币种变成默认的
//     				$goods[$k]['gnum'] = $arr[$goods[$k]['id']]['gnum'];//显示对应的钱数
//     			}else{
//     				unset($goods[$k]);//如果不存在就不默认
//     			}
//     		}  		
    	$account = Db::name('App_account_type')->where(array('jihuo'=>1))->find();//查看激活使用哪个积分
    	$member_account = Db::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->find();//用户积分余额
    	
  		
		$this->assign('account',$account);
		$this->assign('member_account',$member_account['account_type_'.$account['id']]);
//     	$this->assign('goods',$goods);
    	$this->assign('member',$member);
//     	$this->assign('level',$level);
    	return $this->fetch();
    }
    /**
     * 升级页面
     */
    public function shengji(){
    	$session = session::get();
    	//查看后台会员级别
    	$level = Db::name('App_level')->where(array('status'=>1))->select();
    	//$where['member_id'] = $session['USER_KEY_ID'];
    	$where['jihuo'] = 1;
    	$account = Db::name('App_account_type')->where($where)->find();
    	$member_account = Db::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->find();
    	$bb['money'] = $member_account['account_type_'.$account['id']];
    	$bb['name'] = $account['name'];
    	
    	
    	//个人信息
    	//$member = Db::name('App_member_relation')->where(array('member_id'=>$session['USER_KEY_ID']))->find();
    	
    	$member = Db::table('wst_app_member_relation')
							    	->field('a.member_id,a.zhuceid,a.jiedianid,a.quyu,a.level,a.status,a.yeji_left,a.yeji_righ,b.createTime,b.userId,b.loginName as account')
							    	->alias('a')
							    	->join('wst_users b','a.member_id = b.userId')
							    	->where(array('member_id'=>$session['USER_KEY_ID']))
							    	->find();
    	$my_jiedian = Db::name('Users')->where(array('userId'=>$member['jiedianid']))->find();
    	$my_tuijian = Db::name('Users')->where(array('userId'=>$member['zhuceid']))->find();
    	$member['jiedian_name'] = $my_jiedian['loginName'];
    	$member['zhuce_name'] = $my_tuijian['loginName'];
    	foreach($level as $k=>$v){
    		if($level[$k]['id'] <= $member['level'] || $level[$k]['id'] == 5){
    			unset($level[$k]);
    		}
    	}
    	//dump($member);
    	$this->assign('member',$member);
    	$this->assign('bb',$bb);
    	$this->assign('level',$level);
    	return $this->fetch();
    }
    
    
    
    /**
     * 删除用户功能
     */
    public function jihuoDel(){
    	$uid = input('member_id');
    	$member = Db::name('App_member_relation')->where(array('member_id'=>$uid))->find();
    	if($member['status']!=0){
    		$msg['status']=-1;
    		$msg['info']="不要删除已经激活的人";
    		return json($msg);
    	}
    	$res[] = Db::name('App_member_relation')->where(array('member_id'=>$uid))->delete();
    	$res[] = Db::name('Users')->where(array('userId'=>$uid))->delete();
    	$res[] = Db::name('App_member_account')->where(array('member_id'=>$uid))->delete();
    	if($res){
    		$msg['status']=1;
    		$msg['info']="删除成功";
    		return json($msg);
    	}else{
    		$msg['status']=-1;
    		$msg['info']="删除失败";
    		return json($msg);
    	}
    }
    /*************************************************************************************************************************************************
    
    
    
    
     /**
     * 充值
     */
    public function index(){
    	if($_GET['is_pay']!=1){
    		$this->display('Public:404');exit();
    	}
    	//二级密码验证
    	//$this->checkTwoPwd();
    	//session('checkTwoPwd_success',null);
        $config=$this->config;
        $member=$this->member;
        //随机数
        $num =  0.01*rand(10,99);
        $fee=floatval($config['pay_fee']+$num);
        $bank_type = M('Bank_type')->select();
		$this->assign('bank_type',$bank_type);
		$bank = M('Website_bank')->where('status = 1')->select();
        
		$this->assign('bank',$bank);
        $this->assign('fee',$fee);
        return $this->fetch();
    }
    //充值处理
    public function payAjaxReturn(){
    	$config=$this->config;
    	$data['member_name']=I('post.member_name');
    	$data['money']=intval(I('post.money'));
    	$data['account']=I('post.account');
    	$data['count']=I('post.count');
    	$data['type']=1;
    	$data['member_id'] = session('USER_KEY_ID');
    	$data['add_time']=time();
    	$data['status']=0;
    	$data['bank_id']=intval(I('post.bank'));
    	if(empty($data['member_name'])||empty($data['money'])||empty($data['account'])||empty($data['type'])){
    		$arr['info']='请填写全部信息';
    		$arr['status']=0;
    		return json($arr);
    	}
    	if(strlen($data['account'])<11||strlen($data['account'])>20){
    		$arr['info']='请输入正确的银行卡号或支付宝账号';
    		$arr['status']=0;
    		return json($arr);
    	}
    	if($data['money']<$config['pay_min_money']){
    		$arr['info']="充值金额不能小于{$config['pay_min_money']}元";
    		$arr['status']=0;
    		return json($arr);
    	}
    	if($data['money']>$config['pay_max_money']){
    		$arr['info']="充值金额不能大于{$config['pay_max_money']}元";
    		$arr['status']=0;
    		return json($arr);
    	}
    
    	$list=M('KPay')->add($data);
    	//财务日志
    	addKFinanceLog($this->member['member_id'],6,'充值人民币'.$data['money'],$data['money'],1,0);
    	if($list){
    		$arr['info']="充值订单提交成功";
    		$arr['status']=1;
    		$arr['num']=$data['count'];
    		return json($arr);
    	}else{
    		$arr['info']="充值订单提交失败";
    		$arr['status']=0;
    		return json($arr);
    	}
    }
    //充值记录
    public function history(){
    	//二级密码验证
    	$this->checkTwoPwd();
    	session('checkTwoPwd_success',null);
    	//支付表
        $where['member_name']=$this->member['name'];
        $where['member_id']=$this->member['member_id'];
        $where['type'] = array('NEQ',3);
    	//分页
    	$pay = M('KPay'); // 实例化User对象
    	$count = $pay->where($where)->count();// 查询满足要求的总记录数
    	$Page  = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    	$show       = $Page->show();// 分页显示输出
    	$list=$pay->where($where)->order('pay_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	foreach ($list as $k=>$v){
            $list[$k]['status']=payStatus($v['status']);
        }
        //dump($list);die;
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('page',$show);
    	return $this->fetch();
    }
    //提币申请
    public function tibiApplication (){
    	$tibi_min = $this->config['tibi_min'];  //提币最小金额倍数
		$tibi_fee = $this->config['tibi_fee'];  //提币费用比率
		$tibi_max = $this->config['tibi_max'];  //提币最大比率
		$tibi_limit_num = $this->config['tibi_limit_num'];   //提币每月最大次数
		//统计当月已经体现次数
		$start = strtotime(date("Y-m-1 00:00:00",time()));
		$end = time();
		$where['user_id'] = $_SESSION['think']['USER_KEY_ID'];
		$where['add_time'] = array('between',array($start,$end));
		$count = M('Tibi')->where($where)->count();
		//dump($where);die;
		//将数据整理成数组
		$data['tibi_min'] = $tibi_min;
		$data['tibi_fee'] = $tibi_fee;
		$data['tibi_max'] = $tibi_max;
		$data['tibi_limit_num'] = $tibi_limit_num;
		$data['count'] = $count;
		//赋值给前台输出
		$this->assign('data',$data);
    	return $this->fetch();
    }
    //提币历史
    public function tibiHistory (){
    	//二级密码验证
    	//$this->checkTwoPwd();
//     	$where["status"]=array("in",array(4,5));
    	$where["member_id"]=session('USER_KEY_ID');
		$count      = M("Tibi")->where($where)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		//给分页传参数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = M("Tibi")->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		//修改状态
// 		$currency=M("Currency")->where(array("currency_id"=>30))->find();
//     	$this->tibi_save($currency);
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		
		return $this->fetch();
    }
    /**
     * 修改提币记录
     */
    private function tibi_save(){
		//这个地方读取是提币未完成的
    	$where['user_id']=$_SESSION['think']['USER_KEY_ID'];
    	$where['status']=6;
    	$list=M("Tibi")->where($where)->select();
    	if(!empty($list)){
    		foreach ($list as $k=>$v){
    			$x="";
    			$data="";
    			$x=$this->chakan_tibi_jilu($v['ti_id']);
    			if($x['confirmations']>2){
    				$data['check_time']=$x['time'];
    				$data['status']=5;
    				M("Tibi")->where("id='{$v['id']}'")->save($data);
    			}
    		}
    	}
    }
    /**
     *
     * 查看提币记录
     *
     * @param unknown $tid 提币ti_id
     * @return unknown
     */
    private function chakan_tibi_jilu($tid){
    	require_once 'App/Common/Common/easybitcoin.php';
    	$bitcoin = new \Bitcoin($this->rpcuser,$this->rpcpassword,$this->rpcurl,$this->rpcport);
    	$result = $bitcoin->getinfo();
    	$list= $bitcoin->gettransaction($tid);
    	return $list;
    }
    //人工充值AJAX处理方式
    public function rechargeByMan(){
    	$config=$this->config;
    	$member=$this->member;
    	$data['member_name']=I('post.member_name');
    	$data['money']=intval(I('post.money'));
    	$data['account']=I('post.account');
    	$data['count']=I('post.count');
    	$data['type']=I('post.type');	
    	$data['bank_id']=I('post.bank_id');	
    	if(empty($data['member_name'])||empty($data['money'])||empty($data['account'])||empty($data['type'])){
    		$arr['info']='请填写全部信息';
    		$arr['status']=0;
    		return json($arr);
    	}
    	if($member['status']!=1){
    		$arr['info']='请完成实名验证再进行充值';
    		$arr['status']=0;
    		return json($arr);
    	}
    	if(strlen($data['account'])<11||strlen($data['account'])>20){
    		$arr['info']='请输入正确的银行卡号或支付宝账号';
    		$arr['status']=0;
    		return json($arr);
    	}
    	if($data['money']<$config['pay_min_money']){
    		$arr['info']="充值金额不能小于{$config['pay_min_money']}元";
    		$arr['status']=0;
    		return json($arr);
    	}
    	if($data['money']>$config['pay_max_money']){
    		$arr['info']="充值金额不能大于{$config['pay_max_money']}元";
    		$arr['status']=0;
    		return json($arr);
    	}
    	$data['member_id'] = session('USER_KEY_ID');
    	$data['add_time']=time();
    	$data['status']=0;
    	$list=M('Pay')->add($data);
    	$bank=M('Bank_type')->where('bank_id='.$data['bank_id'])->find();
    	if($list){
    		$arr['info']="充值订单提交成功";
    		$arr['status']=1;
    		$arr['num']=$data['count'];
    		$arr['bankname']=$bank['bank_name'];
    		$arr['bankurl']=$bank['bank_url'];
    		$arr['order_id']=$list;
    		return json($arr);
    	}else{
    		$arr['info']="充值订单提交失败";
    		$arr['status']=0;
    		return json($arr);
    	}
    }
   
    
    /**
     * 提币方法
     */
    
    public function ti_bi(){
    	$num=floatval(I('post.num'));
//     	$this->config['tcoin_fee']=5;
    	if(empty($num)){
    		$arr['status']=-1;
    		$arr['info']="请填写提币数量";
    		return json($arr);exit;
    	}
		$paypwd=I('post.paypwd');
    	if(empty($paypwd)){
    		$arr['status']=-4;
    		$arr['info']="请填写支付密码";
    		return json($arr);exit;
    	}
		$qianbao_url=I('post.address');
		if(empty($qianbao_url)){
			$arr['status']=-4;
    		$arr['info']="请填写钱包地址";
    		return json($arr);exit;
		}
    	if($num < $this->config['tibi_min']){
    		$arr['status']=-2;
    		$arr['info']="请填写大于{$this->config['tibi_min']}的数量";
    		return json($arr);exit;
    	}
		if($num % ($this->config['min']) != 0){
			$arr['status']=-3;
    		$arr['info']="请填写{$this->config['tibi_min']}的倍数的提币数量";
    		return json($arr);exit;
		}
		
		$user=M("Member")->where("member_id='{$_SESSION['think']['USER_KEY_ID']}'")->find();
     	if($num > ($this->config['tibi_max'] * $user['integral'])){
     		$arr['status']=-6;
			$arr['info']="本次最大提币数量为".($this->config['tibi_max'] * $user['integral']).",已经超出此限制";
    		return json($arr);exit;
     	}
		$start = strtotime(date("Y-m-1 00:00:00",time()));
		$end = time();
		$where['user_id'] = $_SESSION['think']['USER_KEY_ID'];
		$where['add_time'] = array('between',array($start,$end));
		$count = M('Tibi')->where($where)->count();
		unset($where);
		if($count >= $this->config['tibi_limit_num']){
			$arr['status']=-7;
			$arr['info']="本月已经没有提币次数了";
    		return json($arr);exit;
		}
		
		
    	
    	$user=M("Member")->where("member_id='{$_SESSION['think']['USER_KEY_ID']}'")->find();
    	if($user['pwdtrade']!=md5($_POST['paypwd'])){
    		$arr['status']=-5;
    		$arr['info']="支付密码错误";
    		return json($arr);exit;
    	}
    	
    	//判断看这个钱包地址是否是真实地址   
//     	if(!$this->check_qianbao_address($qianbao_url)){
//     		$arr['status']=-6;
//     		$arr['info']="提币地址不是一个有效地址";
//     		return json($arr);exit;
//     	}
    	//判断账户余额够不够
    	if($user['integral']<$num){
    		$arr['status']=-7;
    		$arr['info']="账户余额不足，无法提币";
    		return json($arr);exit;
    	}
    	if(!empty($this->config['tibi_fee'])){
    		$actual=$num*(1-$this->config['tibi_fee']/100);//计算出扣除手续费后的价格
    		
    	}else{
    		$actual=$num;
    	}
    	$actual=(float)$actual;//实际到账
    
    	$data['fee']=$this->config['tcoin_fee']?$this->config['tcoin_fee']:0;//手续费
//     	$data['currency_id']=30;
    	$data['user_id']=$_SESSION['think']['USER_KEY_ID'];
    	$data['url']=$qianbao_url;
    	$data['name']=$user['account'];
    	$data['num']=$num;
    	$data['actual']=$actual;//实际到账价格 
    	$data['status']=4;//需要审核
    	$data['add_time']=time();
    	
//     	$tibi=$this->qianbao_tibi($qianbao_url,$actual);//提币程序
   		$re=M("Tibi")->add($data);
    	if($re){//成功写入数据库
//     		$data['ti_id']=$tibi;
    		//减钱操作
    		M("Member")->where("member_id = '{$_SESSION['think']['USER_KEY_ID']}'")->setDec("integral",$num);
    		$arr['status']=1;
    		$arr['info']="提币成功，请耐心等待";
    		return json($arr);exit;
    
    	}else{//失败提示
    		$arr['status']=-8;
    		$arr['info']="提币失败";
    		return json($arr);exit;
    	}
    	 
    	 
    	 
    }
    /**
     * 提币引用的方法
     * @param unknown $url 钱包地址
     * @param unknown $money 提币数量
     * 
     * 需要加密 *********************
     */
    private function qianbao_tibi($url,$money){
    	require_once 'App/Common/Common/easybitcoin.php';
    		$bitcoin = new \Bitcoin($this->rpcuser,$this->rpcpassword,$this->rpcurl,$this->rpcport);
//     	$result = $bitcoin->getinfo();
    	$bitcoin->walletlock();//强制上锁
    	$bitcoin->walletpassphrase($this->rpckey,20);
    	$id=$bitcoin->sendtoaddress($url,$money);
    	$bitcoin->walletlock();
    	return $id;
    }
    public function rpc2(){
    	require_once 'web/Common/Common/Common/easybitcoin.php';
    	$bitcoin = new \Bitcoin('user','passwd','localhost','29991');
    	$result = $bitcoin->getinfo();
    	$id= $bitcoin->sendtoaddress('LXUVqocGoVivuEXd4SPquZC3W5eW7DVCMD',0.00001);
    
    }
    /**
     * 获取新的一个钱包地址
     * @return unknown
     */
    private function qianbao_new_address(){
    	require_once 'App/Common/Common/easybitcoin.php';
   
    	$bitcoin = new \Bitcoin($this->rpcuser,$this->rpcpassword,$this->rpcurl,$this->rpcport);
//     	dump($bitcoin);
    	$user=$_SESSION['KAdmin_userid'];
    	$x=$bitcoin->getinfo();
//     	dump($x);
//     	dump($user);
    	$address = $bitcoin->getnewaddress($user);
//     	dump($address);
    
    	return $address;
    }
    /**
     * 检测地址是否是有效地址
     *
     * @return boolean 如果成功返回个true
     * @return boolean 如果失败返回个false；
     *  @param unknown $url
     *  @param $port_number 端口号 来区分不同的钱包
     */
    private function check_qianbao_address($url){
    	
    	require_once 'App/Common/Common/easybitcoin.php';
 		$bitcoin = new \Bitcoin($this->rpcuser,$this->rpcpassword,$this->rpcurl,$this->rpcport);
    	$address = $bitcoin->validateaddress($url);
    	if($address['isvalid']){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    
    
    /**
     * 12.3褚天恩
     * 艺尊指数提币
     * 前台提交后台审核
     */
   	public function yizun(){
   		$uid = $_SESSION['think']['USER_KEY_ID'];
   		$user = M('Member')->where(array('member_id'=>$uid))->find();
   		$list = M('Yizun_tixian')->where(array('member_id'=>$uid))->select();
   		$this->assign('list',$list);
   		$this->assign('user',$user);
   		return $this->fetch();
   	}
    /**
     * 提交审核
     */
    public function tixianShenHe(){
    	$num = I('num')?I('num'):null;
    	$pwd = I('pwd')?md5(I('pwd')):null;
    	
    	$code = I('code')?I('code'):null;
    	if(empty($pwd)){
    		$data['info'] = "请输入二级密码";
    		$data['status'] = -3;
    		return json($data);
    	}
    	if(empty($num)){
    		$data['info'] = "请输入提现金额";
    		$data['status'] = -1;
    		return json($data);
    	}
    	if(empty($code)){
    		$data['info'] = "请输入验证码";
    		$data['status'] = -10;
    		return json($data);
    	}
    	if($code != $_SESSION['code']){
    		$data['info'] = "验证码有误";
    		$data['status'] = -11;
    		return json($data);
    	}
    	if($num<0){
    		$data['info'] = "请输入正确的金额";
    		$data['status'] = -2;
    		return json($data);
    	}
    	$uid = $_SESSION['think']['USER_KEY_ID'];
    	$member = M('Member')->where(array('member_id'=>$uid))->find();
    	if($pwd != $member['pwdtrade']){
    		$data['info'] = "二级密码错误";
    		$data['status'] = -4;
    		return json($data);
    	}
    	if($num>$member['gupiao_num']){
    		$data['info'] = "账户余额不足";
    		$data['status'] = -6;
    		return json($data);
    	}
    	$arr['member_id'] = $uid;
    	$arr['status'] = 0;
    	$arr['add_time'] = time();
    	$arr['num'] = $num;
    	$res = M('Yizun_tixian')->add($arr);
    	$re = M('Member')->where(array('member_id'=>$uid))->setDec('gupiao_num',$num);
    	if($res){
    		$data['info'] = "提现成功";
    		$data['status'] = 1;
    		return json($data);
    	}else{
    		$data['info'] = "系统繁忙";
    		$data['status'] = -7;
    		return json($data);
    	}
    	
    }
    
    
    /**
     * ajax 发送手机号码
     */
    public function ajaxSandPhone(){
    	$member_id = $_SESSION['think']['USER_KEY_ID'];
    	$user = M('Member')->where(array('member_id'=>$member_id))->find();
    	$phone = $user['phone'];
// 		dump($phone);
    	$code=rand(1000, 9999);
    	session(array('name'=>'code','expire'=>600));
    	session('code',$code);  //设置session
    	session('time',time());
    	$msg="【艺尊宝】您的验证码为".$code."，请不要泄漏给他人！";//要发送的短信内容
    	$re=sendSMS($phone, $msg);
//     	dump($re);
    	$result=preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $re['1'], $matches);
    	if($result == 1){
    		$arr['status']=1;
    		$arr['info']="发送成功";
    	}else{
    		$arr['status']= -1;
    		$arr['info']="发送失败";
    	}
    	return json($arr);
    	 
    }

	/**
	*市场服务奖 
	*/
	public function fuwu(){
		$where["member_id"]=$_SESSION['think']['USER_KEY_ID'];
		$where['type'] = 32;
		$count      = M("Finance")->where($where)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		//给分页传参数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = M("Finance")->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		//修改状态
// 		$currency=M("Currency")->where(array("currency_id"=>30))->find();
//     	$this->tibi_save($currency);
		//dump($list);die;
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		return $this->fetch();
	}
	/**
	*市场分享奖
	*/
	public function fenxiang(){
		$where["member_id"]=$_SESSION['think']['USER_KEY_ID'];
		$where['type'] = 24;
		$count      = M("Finance")->where($where)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		//给分页传参数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = M("Finance")->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		return $this->fetch();
	}
    /**
	*充币界面
	*/
	public function chongbiApplication(){
		$member = M("Member")->where("member_id={$_SESSION['think']['USER_KEY_ID']}")->find();
		if($member['pl_address'] == ''){
			$address = $this->qianbao_new_address();
			if(!empty($address)){
				M('Member')->where("member_id={$_SESSION['think']['USER_KEY_ID']}")->setField('pl_address',$address);				
			}
		}else{
			$address = $member['pl_address'];
		}
		$where['status']=array('in',array(2,3));
		$where['user_id']=$_SESSION['think']['USER_KEY_ID'];
		//充币记录
		import('ORG.Util.Page');// 导入分页类
		$count      = M('Tibi')->where($where)->count ();// 查询满足要求的总记录数
		$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		$list=M('Tibi')
		->field('url,add_time,status,num,fee,actual,check_time')
		->where($where)
		->limit($Page->firstRow.','.$Page->listRows)
		->order('add_time desc')
		->select();
		$this->assign('list',$list);
		$this->assign('address',$address);
		return $this->fetch();
	}
    /**
     * 充值方法
     * @return boolean
     */
    
    public function chongzhi_function(){
		//echo $_SESSION['userid'];
    	$list=$this->trade_qianbao($_SESSION['think']['USER_KEY_ID']);
		//dump($list);
    	foreach ($list as $k=>$v){
    		//$data["currency_id"]=$currency['currency_id'];//货币id写入
    		if($v['category']=='receive'){
    			$data[]=array();
    			$data['user_id']=$_SESSION['think']['USER_KEY_ID'];
    			$data['url']=$v['address'];//地址
    			$data['name']=$v['account'];//标签
    			$data['add_time']=$v['time'];//时间
    			$data['num']=$v['amount'];//数量
    			$data['fee']=0;
				$where['status'] = array('in',array(2,3));
				$where['ti_bi'] = $v['txid'];
    			$tibi_txid=M("Tibi")->where($where)->find();
    			if(!empty($tibi_txid)){
    				//如果已经存在  而且是已经完成状态 不处理直接跳出循环
    				if($tibi_txid['status']==3){
    					continue;
    				}
    				if($v['confirmations']>2){
    					$data['status']=3;//3表示充值完成
    					$data['check_time']=$v['timereceived'];//确认时间
    					$re=M("Tibi")->where("ti_id='{$v['txid']}'")->save($data);//修改状态 表示已经完成
    					M("Member")->where("member_id='{$_SESSION['think']['USER_KEY_ID']}'")->setInc("integral",$v['amount']);//给User表加钱
    				}
    			}else{
    				$data['ti_id']=$v['txid'];//写入交易id号
    				if($v['confirmations']>2){
    					$data['status']=3;//3表示充值完成
    					$data['check_time']=$v['timereceived'];//确认时间
    					$re=M("Tibi")->add($data);//修改状态 表示已经完成
    					M("Member")->where("member_id='{$_SESSION['think']['USER_KEY_ID']}'")->setInc("integral",$v['amount']);//给User表加钱
    				}else{
    					$data['status']=2;//2表示充值中
    					$re=M("Tibi")->add($data);
    				}
    			}    
    		}
    	}
    	if($re){
    		$arr['status']=1;
    		return json($arr);
    	}
    }
    /**
     * 查询某人的交易记录
     * @param unknown $user 用户名
     * @param unknown $count  从第几个开始查找
     * @return $list  返回此用户的交易列表
     */
    private function trade_qianbao($user){
    	require_once 'App/Common/Common/easybitcoin.php';
   	    $bitcoin = new \Bitcoin($this->rpcuser,$this->rpcpassword,$this->rpcurl,$this->rpcport);
    	//$result = $bitcoin->getinfo();
    	$list=$bitcoin->listtransactions($user,10,0);
    	return $list;
    }
}